package com.webtest.authoritydemo;

import com.webtest.filter.AbstractHttpFilter;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author liuziyang
 * @create 2018-08-19 18:02
 */
public class AuthorityFilter extends AbstractHttpFilter {
    private UserDao userDao = new UserDao();

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 获取访问路径，类似/authdemo/login.jsp
        String path = request.getServletPath();
        // 根据不需要过滤的页面列表，直接将不需要过滤的页面返回
        // 从配置文件中读取不需要过滤的url列表
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("uncheckedurls.ini");
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        List<String> uncheckedUrls = new ArrayList<>();
        String url;
        while ((url = reader.readLine()) != null) {
            uncheckedUrls.add(url);
        }

        if (uncheckedUrls.contains(path)) {
            chain.doFilter(request, response);
            return;
        }

        // 对需要进行过滤的页面进行处理
        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute("loginName");
        // 判断登陆用户状态，防止出现用户已经登出或者权限配置变化的情况
        if (StringUtils.isEmpty(userName)) {
            request.setAttribute("message", "用户已登出，请重新登录");
            request.getRequestDispatcher("/authdemo/login.jsp");
            return;
        }
        if (!userDao.exit(userName)) {
            request.setAttribute("message", "用户状态异常，请重新登录");
            request.getRequestDispatcher("/authdemo/login.jsp");
            return;
        }
        // 如果授权通过，则通过，否则跳转到无授权页面
        if (hasAuth(userName, path)) {
            chain.doFilter(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/authdemo/noauth.jsp");
        }
    }

    @Override
    protected void init() {

    }

    private boolean hasAuth(String userName, String path) {
        User user = userDao.get(userName);
        List<Authority> authorities = user.getAuthorities();
        List<String> paths = new ArrayList<>();
        authorities.forEach(authority -> paths.add(authority.getUrl()));
        return paths.contains(path);
    }
}
